<template>
  <el-dialog class="dia-style" :title="title" :visible.sync="isOpen" :close-on-click-modal="false" width="1200px">
    <div class="h-container">
      <div v-if="formData.type == 0" class="left">
        <el-tree
          ref="tree"
          :data="deptOptions"
          :props="defaultProps"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          default-expand-all
          highlight-current
          @node-click="handleNodeClick"
        />
      </div>
      <div class="right">
        <el-form ref="tableForm" :model="model" @submit.native.prevent>
          <el-table ref="tableData" v-loading="loading" :data="model.roleList">
            <el-table-column label="序号" align="center" width="60">
              <template slot-scope="scop">
                {{ scop.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="字段名称" show-overflow-tooltip prop="columnName" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-form-item
                  v-if="scope.row.isNew == true"
                  :prop="'roleList.' + scope.$index + '.columnName'"

                  :rules="{
                    required: true,
                    type: 'string',
                    min: 1,
                    message: '请输入字段名称',
                    trigger: 'blur',
                  }"
                >
                  <el-input
                    v-model="scope.row.columnName"
                    placeholder="请输入字段名称"
                    maxlength="50"
                    show-word-limit
                  />
                </el-form-item>

                <span v-else class="formitem-elips">{{ scope.row.columnName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="字段类型" prop="columnType" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-form-item v-if="scope.row.isNew == true">
                  <el-select v-model="scope.row.columnType" placeholder="请选择">
                    <el-option
                      v-for="(item, index) in options"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    /> </el-select></el-form-item>

                <span v-else>{{ typeOfObj(scope.row.columnType) }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="formData.type == 1" label="字段长度" prop="columnSize">
              <template slot-scope="scope">
                <el-form-item
                  v-if="scope.row.isNew == true"
                  :prop="'roleList.' + scope.$index + '.columnSize'"
                  :rules="[
                    {
                      required: true,
                      message: '请输入字段长度',
                      trigger: 'blur',
                    },
                    { type: 'number', message: '必须是数字', trigger: 'blur' },
                  ]"
                >
                  <el-input v-model.number="scope.row.columnSize" placeholder="请输入字段长度" />
                </el-form-item>

                <span v-else>{{ scope.row.columnSize }}</span>
              </template>
            </el-table-column>
            <el-table-column label="是否自动填充" prop="autoFilling">
              <template slot-scope="scope">
                <el-form-item v-if="scope.row.isNew == true">
                  <el-select v-model="scope.row.autoFilling" placeholder="请选择">
                    <el-option
                      v-for="item in keyWordOption"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <span v-else>{{ scope.row.autoFilling == 1 ? '是' : '否' }}</span>
              </template>
            </el-table-column>
            <el-table-column v-if="formData.type == 0" label="字段默认值" prop="columnDef" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-form-item v-if="scope.row.isNew == true">
                  <el-input v-model="scope.row.columnDef" placeholder="请输入默认值" maxlength="765" />
                </el-form-item>
                <span v-else class="formitem-elips">{{ scope.row.columnDef }}</span>
              </template>
            </el-table-column>
            <el-table-column v-else label="默认值" prop="defaultValue" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <el-form-item v-if="scope.row.isNew == true">
                  <el-input v-model="scope.row.defaultValue" placeholder="请输入默认值" maxlength="765" />
                </el-form-item>
                <span v-else class="formitem-elips">{{ scope.row.defaultValue }}</span>
              </template>
            </el-table-column>

            <el-table-column v-if="formData.type == 1" label="是否非空" prop="columnIsnull">
              <template slot-scope="scope">
                <el-form-item v-if="scope.row.isNew == true">
                  <el-select v-model="scope.row.columnIsnull" placeholder="请选择">
                    <el-option v-for="item in columnOption" :key="item.label" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
                <span v-else>{{ scope.row.columnIsnull == 1 ? '是' : '否' }}</span>
              </template>
            </el-table-column>

            <el-table-column label="字段描述" show-overflow-tooltip prop="columnDesc">
              <template slot-scope="scope">
                <el-form-item
                  v-if="scope.row.isNew == true"
                  :prop="'roleList.' + scope.$index + '.columnName'"
                  :rules="{
                    required: true,
                    type: 'string',
                    min: 1,
                    message: '请输入字段描述',
                    trigger: 'blur',
                  }"
                >
                  <el-input v-model="scope.row.columnDesc" placeholder="请输入字段描述" maxlength="50" />
                </el-form-item>
                <span v-else class="formitem-elips">{{ scope.row.columnDesc }}</span>
              </template>
            </el-table-column>

            <el-table-column
              v-show="formData.type == 0"
              label="操作"
              align="center"
              class-name="small-padding fixed-width"
            >
              <template v-if="scope.row.useState != 0" slot-scope="scope">
                <el-switch
                  v-model="scope.row.useState"
                  :active-value="1"
                  :inactive-value="2"
                  @change="handleChange(scope.row)"
                />
                <span style="margin-left: 10px">{{ scope.row.useState == 1 ? '启用' : '弃用' }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
        <el-button
          style="border: 1px dashed #2979ff; width: 100%"
          icon="el-icon-plus"
          @click="handleAddRow"
        >新增一行</el-button>
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">保 存</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  queryJson,
  queryTable,
  addTable,
  addJson,
  querySon,
  itemType,
  metaDetails
} from '@/api/milkyway/metaDataManagement'
export default {
  name: 'UpholdDialog',
  props: {
    title: {
      type: String,
      default() {
        return '编辑'
      }
    },
    form: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      formData: {},
      model: {
        roleList: [
          {
            columnSize: 0
          }
        ]
      },
      // 部门树选项
      deptOptions: [],
      defaultProps: {
        children: 'children',
        label: 'columnName'
      },
      isOpen: false,
      loading: false,
      options: [],
      keyWordOption: [
        {
          label: '是',
          value: 1
        },
        {
          label: '否',
          value: 0
        }
      ],
      columnOption: [
        {
          label: '是',
          value: 1
        },
        {
          label: '否',
          value: 0
        }
      ],
      queryParams: {},
      parentId: this.form.id
    }
  },
  computed: {},
  watch: {
    formData(newValue, oldValue) {
      // this.getList(newValue.id);
    }
  },
  mounted() {},
  methods: {
    typeOfObj(t) {
      if (t) {
        const obj = this.options.find((o) => {
          return o.value === t
        })
        if (obj) {
          return obj.label
        }
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.parentId = data.id
      console.log(data.id)
      this.queryParams.current = 1
      this.getList()
    },
    // 获取字典数据
    getType() {
      this.$nextTick(() => {
        const type = this.formData.type == 0 ? 'structureColumnType' : 'relationColumnType'

        itemType(type).then((res) => {
          this.options = []
          res.forEach((item) => {
            this.options.push({
              label: item.itemLabel,
              value: item.itemVale
            })
          })
        })
      })
    },
    show(id) {
      return new Promise((resolve, reject) => {
        metaDetails(id)
          .then((res) => {
            this.formData = res
            resolve(this.formData)
          })
          .then(() => {
            this.isOpen = true
            this.getList(id)
            this.parentId = id
            this.getTree(id)
            this.getType()
          })
      })
    },
    /** 查询列表 */
    getList(rid) {
      const id = rid || (this.formData.type == 0 && this.parentId ? this.parentId : this.formData.id)

      if (id) {
        this.loading = true

        if (this.formData.type == 1) {
          queryTable(this.formData.id).then((res) => {
            this.model.roleList = res
            this.loading = false
          })

          return
        } else {
          querySon(id).then((res) => {
            this.model.roleList = res
            this.loading = false
          })
        }
      }
    },
    // 提交操作
    submitForm() {
      this.$refs['tableForm'].validate((valid) => {
        if (valid) {
          if (this.formData.type == 0) {
            addJson(this.model.roleList)
              .then((response) => {
                this.$modal.msgSuccess('保存json数据成功')
                this.isOpen = false
                this.resetForm()
                this.getList(this.formData.id)
                this.getTree(this.formData.id)
                this.$emit('submitForm')
              })
              .catch((err) => {
                console.log(err)
              })
          } else {
            addTable(this.model.roleList).then((response) => {
              this.$modal.msgSuccess('保存二维表数据成功')
              this.isOpen = false
              this.resetForm()
              this.getList(this.formData.id)
              this.getTree(this.formData.id)
              this.$emit('submitForm')
            })
          }
        }
      })
    },
    resetForm() {
      this.$refs['tableForm'].resetFields()
    },
    cancel() {
      this.isOpen = false
      this.deptOptions = []
      this.model = {
        roleList: [
        ]
      }
    },
    handleChange(row) {
      // this.model.roleList[row].useState = 1;
    },
    // 新增
    handleAddRow() {
      if (this.formData.type == 0) {
        this.model.roleList.push({
          parentId: this.parentId,
          isNew: true,
          columnName: undefined,
          columnType: undefined,
          columnIsnull: undefined,
          autoFilling: 0,
          defaultValue: undefined,
          columnSize: 0,
          columnDesc: undefined,
          mdId: this.formData.id
        })
        this.getType()
      } else {
        this.model.roleList.push({
          isNew: true,
          columnName: undefined,
          columnType: undefined,
          columnIsnull: undefined,
          autoFilling: 0,
          defaultValue: undefined,
          columnSize: undefined,
          columnDesc: undefined,
          mdId: this.formData.id
        })
        this.getType()
      }
    },
    // 加载树结构
    getTree(id) {
      queryJson(id).then((res) => {
        if (res) {
          this.deptOptions = []
          if (res.structChild) {
            const dep = res
            dep.columnName = res.mdName
            dep.children = res.structChild
            this.deptOptions.push(dep)
          } else {
            this.deptOptions.push({
              columnName: res.mdName,
              children: res.structChild
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.formitem-elips{
  display:inline-block;width:100%;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;
}
.h-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  .left {
    width: 15%;
    height: 100%;
    overflow: auto;
  }
  .right {
    margin-top: -20px;
    flex: 1;
    height: 100%;
    overflow: auto;
  }
  .el-form-item {
    margin-bottom: 0 !important;
  }
}
::v-deep {
  .el-table__row {
    height: 70px;
  }
  .el-table td.el-table__cell div {
    overflow: visible;
  }
  .el-table--medium .el-table__cell {
    padding: 0px;
  }
}
</style>
